package com.xieshue.im.handler.codec;

import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 消息编码器
 *
 * @author xieshue
 * @date 2017\12\22 0022
 */
public class ImMessageEncoder extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        byte[] body = msg.toByteArray();
        byte[] head = new byte[4];
        System.arraycopy(byteToInt(body.length), 0, head, 0, 4);
        out.writeBytes(head);
        out.writeBytes(body);
    }

    private byte[] byteToInt(int len) {
        byte[] b = new byte[4];
        b[0] = (byte) (len >> 24 & 0xff);
        b[1] = (byte) (len >> 16 & 0xff);
        b[2] = (byte) (len >> 8 & 0xff);
        b[3] = (byte) (len & 0xff);
        return b;
    }
}
